package io.gitee.xjt2016.modules.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.gitee.xjt2016.modules.domain.Field;
import io.gitee.xjt2016.modules.mapper.FieldMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FieldService extends ServiceImpl<FieldMapper, Field> {

    @Autowired
    InterfaceService interfaceService;

//    @Trace
    public Field getField(Long fieldId) {
//        ActiveSpan.tag("mp", "芋道源码");
//        System.out.println("traceId：" + TraceContext.traceId());
        Field field = this.baseMapper.selectById(fieldId);
        if (field != null) {
            field.setAnInterface(interfaceService.getInterface(field.getInterfaceId()));
        }
        return field;
    }

    public List<Field> getFieldsByInterfaceId(Long interfaceId) {
        LambdaQueryWrapper<Field> wrapper = Wrappers.lambdaQuery(Field.class);
        wrapper.eq(Field::getInterfaceId, interfaceId);
        return this.list(wrapper);
    }

    public List<Field> getFieldsByInterfaceId(Long interfaceId, String type) {
        LambdaQueryWrapper<Field> wrapper = Wrappers.lambdaQuery(Field.class);
        wrapper.eq(Field::getInterfaceId, interfaceId);
        wrapper.eq(Field::getType, type);
        return this.list(wrapper);
    }

    @Transactional
    public void saveByInterfaceIdAndType(List<Field> fields, Long interfaceId, String type) {
        LambdaQueryWrapper<Field> wrapper = Wrappers.lambdaQuery(Field.class);
        wrapper.eq(Field::getInterfaceId, interfaceId);
        wrapper.eq(Field::getType, type);

        Set<Long> ids = fields.stream().map(Field::getFid).collect(Collectors.toSet());
        ids.add(0L);
        fields = fields.stream().filter(field -> ids.contains(field.getPid())).collect(Collectors.toList());

        this.baseMapper.delete(wrapper);
        this.saveBatch(fields);
    }
}
